/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import { Button, Dialog, Form, ResponsiveGrid, Icon, Input, Switch, DatePicker, Message } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, column, partnerModal, DATETIME_TEXT, toSelectDataSource, ENUMS } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import AttachmentForm from './AttachmentForm';
import QR from '@/components/QR/QR';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import Styles from './DataForm.module.scss'

const { Cell } = ResponsiveGrid;

const FromItem = Form.Item;

const DataForm = ({ modal, username, onCancel, onSubmit }) => {
  const { partnerStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'partner');
  const [QRModal, setQRModal] = useState({});
  const formProps = isViewMode ? { field: false } : {};
  const [partner] = useState(() => observable({}));
  const [cashBackRates, setCashBackRates] = useState({});
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (username) {
      (async () => {
        const cashBackRate = await store.getDictsItems('cashBackRate');
        setCashBackRates(cashBackRate);
        const res = await store.api.get({ search: { username }, pg: { page: 0, size: 10 } });
        const data = res[0];
        editCtx.origin = _.cloneDeep(data);
        _.assign(partner, data);
        store.getCompany({ search: { status: 1 }, pg: { size: 999 } });
        // _.set(partner, 'partnerInfo.discountInfo.disable', !initDisable);
      })();
    } else {
      _.set(partner, 'partnerInfo.independentAccount.period', 0);
    }
  }, [username]);

  if (!partner) return <></>;

  const cc = partner?.partnerInfo?.discountInfo?.cc?.type === '1';
  const bus = partner?.partnerInfo?.discountInfo?.bus?.type === '1';
  const sc = partner?.partnerInfo?.discountInfo?.sc?.type === '1';
  const rs = partner?.partnerInfo?.discountInfo?.rs?.type === '1';

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(partner, name, value);
    // 联动效果可以在这里通过设置channel属性实现
    if (name === 'partnerInfo.discountInfo.cc.discountValue.RMB') {
      _.set(partner, 'partnerInfo.discountInfo.cc.discountValue.HKD', value);
      _.set(partner, 'partnerInfo.discountInfo.cc.discountValue.MOP', value);
    }
    if (name === 'partnerInfo.discountInfo.bus.discountValue.RMB') {
      _.set(partner, 'partnerInfo.discountInfo.bus.discountValue.HKD', value);
      _.set(partner, 'partnerInfo.discountInfo.bus.discountValue.MOP', value);
    }
    if (name === 'partnerInfo.discountInfo.sc.discountValue.RMB') {
      _.set(partner, 'partnerInfo.discountInfo.sc.discountValue.HKD', value);
      _.set(partner, 'partnerInfo.discountInfo.sc.discountValue.MOP', value);
    }
    if (name === 'partnerInfo.discountInfo.rs.discountValue.RMB') {
      _.set(partner, 'partnerInfo.discountInfo.rs.discountValue.HKD', value);
      _.set(partner, 'partnerInfo.discountInfo.rs.discountValue.MOP', value);
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    partnerInfo: {
      independentAccount: {
        collectionAccountInformation: {
          name: {
            label: t`真实姓名`,
          },
          accountIdentification: {
            label: t`账号标识`,
            ui: {
              renderer: (v) => (<Input
                value={v}
                placeholder={t`请扫码绑定收款帐号`}
                addonAfter={isViewMode ? null : <Button type="primary" onClick={handleQrCode}>{t`扫码设置`}</Button>}
              />),
            },
          },
        },
      },
      discountInfo: {
        label: t`分佣信息`,
        disable: {
          label: t`是否禁用`,
          ui: {
            renderer: (v) => {
              return (<Switch
                checked={v}
                size="small"
                autoWidth
                checkedChildren="是"
                unCheckedChildren="否"
              />);
            },
          },
        },
        failureTime: {
          label: t`失效时间`,
          text: DATETIME_TEXT,
          ui: {
            renderer: (v) => <DatePicker type="datetime" showTime value={v} />,
          },
        },
        bus: {
          label: t`巴士分佣信息`,
          type: {
            label: t`巴士分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['busType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: bus ? t`巴士分佣值[key]` : t`巴士分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['bus'] : v} />,
              },
            },
          },
        },
        cc: {
          label: t`包车分佣信息`,
          type: {
            label: t`包车分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['ccType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: cc ? t`包车分佣值[key]` : t`包车分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['cc'] : v} />,
              },
            },
          },
        },
        sc: {
          label: t`专线分佣信息`,
          type: {
            label: t`专线分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['scType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: sc ? t`专线分佣值[key]` : t`专线分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['sc'] : v} />,
              },
            },
          },
        },
        rs: {
          label: t`拼车分佣信息`,
          type: {
            label: t`拼车分佣类型`,
            ui: {
              renderer: (v) => <TauSimpleSelect className={v ? '' : Styles.red_select_color} data={toSelectDataSource(ENUMS.type)} value={v == undefined ? cashBackRates['rsType'] : v} />,
            },
          },
          discountValue: {
            label: t`分佣值<br/> RMB<br/> HKD<br/> MOP`,
            '{RMB}': {
              label: rs ? t`拼车分佣值[key]` : t`拼车分佣比例`,
              ui: {
                renderer: (v) => <Input className={v ? '' : Styles.red_input_color} value={v == undefined ? cashBackRates['rs'] : v} />,
              },
            },
          },
        },
      },
      cashBackRate: {
        label: t`返现率<br/> bus 巴士票返现率：默认0<br/> charteredBus 包车返现率：默认0.05<br/> shuttleBus 班车票返现率：默认0.1`,
        bus: {
          label: t`巴士票返现率`,
          ui: {
            renderer: (v) => <Input value={v || cashBackRates['bus']} />,
            itemProps: { required: true },
          },
        },
        cc: {
          label: t`包车票返现率`,
          ui: {
            renderer: (v) => <Input value={v || cashBackRates['cc']} />,
            itemProps: { required: true },
          },
        },
        sc: {
          label: t`专线票返现率`,
          ui: {
            renderer: (v) => <Input value={v || cashBackRates['sc']} />,
            itemProps: { required: true },
          },
        },
        rs: {
          label: t`拼车票返现率`,
          ui: {
            renderer: (v) => <Input value={v || cashBackRates['rs']} />,
            itemProps: { required: true },
          },
        },
      },
      mobile: {
        label: t`手机号`,
        ui: {
          renderer: (v) => <Input value={v} readOnly={modal[0] === 'edit'} />,
          itemProps: { required: true },
        },
      },
    },
  };

  // 扫码绑定用户
  const handleQrCode = async () => {
    try {
      const { fullname } = toJS(partner);
      const baseUrl = await store.addProfitShare(partner);
      setQRModal({
        open: true,
        name: fullname,
        baseUrl,
        okText: '下载',
        onCancel: QROnCancel,
      });
    } catch (error) {
      console.log('🚀 _ file: DataForm.jsx:254 _ error:', error);
    }
  };

  // 关闭二维码
  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  /**
   * @description 提交表单实现修改用户
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const discountInfo = toJS(partner).partnerInfo?.discountInfo || {};
    _.forEach(discountInfo, (value, key) => {
      if (!(key == 'disable' || key == 'failureTime') && discountInfo[key]) {
        if ((!discountInfo[key]?.type && discountInfo[key]?.discountValue?.RMB) || (discountInfo[key]?.type && !discountInfo[key]?.discountValue?.RMB)) {
          if (!discountInfo[key]?.type) {
            discountInfo[key].type = cashBackRates[`${key}Type`];
          }
          if (!discountInfo[key]?.discountValue?.RMB) {
            discountInfo[key] = {
              ...discountInfo[key],
              discountValue: {
                RMB: cashBackRates[key],
                MOP: cashBackRates[key],
                HKD: cashBackRates[key],
              },
            };
          }
        }
      }
    });

    _.assign(partner, {
      partnerInfo: {
        ...partner.partnerInfo,
        discountInfo,
      },
    });

    onSubmit?.(partner);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={partner}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={partner}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['partnerInfo.type', 'fullname', 'mobile', 'gender',
          'email', 'partnerInfo.bindingPeriod', 'partnerInfo.bindingPeriodDesc',
          'partnerInfo.address']}
      />
      <TitleGrid title={t`分账信息`} />
      <FieldsGrid
        formData={partner}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['period', 'suspensionOfDistribution'].map((n) => `partnerInfo.independentAccount.${n}`)}
      />
      <TitleGrid title={t`分佣信息`} />
      <div><strong style={{ color: 'red' }}>{t`提示：红色字体代表默认使用字典配置的分佣类型和比例。`}</strong></div>
      <FieldsGrid
        formData={partner}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['cc.type', 'cc.discountValue.{RMB}', 'sc.type', 'sc.discountValue.{RMB}', 'bus.type', 'bus.discountValue.{RMB}', 'rs.type', 'rs.discountValue.{RMB}', 'disable'].map((n) => `partnerInfo.discountInfo.${n}`)}
      />
      <TitleGrid title={t`备注信息`} />
      <FieldsGrid
        formData={partner}
        mode={modal[0]}
        fields={['partnerInfo.remark']}
      />

      <AttachmentPanel partner={partner?.partnerInfo} mode={modal[0]} />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <QR modal={QRModal} />
    </Form>
  );
};

const AttachmentPanel = observer(({ partner, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'check';

  useEffect(() => {
    if (partner?.attachments?.length) setIdx(0);
  }, [partner?.attachments]);

  const handleAddAttachment = () => {
    if (!partner?.attachments) partner.attachments = [];
    partner.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(partner.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    partner.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={7}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(partner?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, partnerModal?.partnerInfo.attachments[0]),
              column('description', {}, partnerModal?.partnerInfo.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`partner:${partner.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(partner.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              partner.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              partner.attachments[idx]?.binaryId.splice(partner.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(partner.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(DataForm);
